import threading

##
# Clock
# gera clocks do relogio logico
#
class Clock:
    
    ##
    # construtor
    # inicia relogio como zero e inicia mutex
    def __init__( self ):
        self.ck = 0
        self.mutexCk = threading.Condition();

    ##
    # getCk
    # pega o clock atual
    # @return int equivalente ao valor do clock atual
    def getCk( self ):
        self.mutexCk.acquire()
        self.resp = self.ck
        self.mutexCk.release()    
        return self.resp

    ##
    # newCk
    # gera novo clock, compara com clock de referencia e com
    # o proprio e escolhe o maior, adiciona + 1
    # @return int novo clock       
    def newCk( self, ckRef ):
        ckRef = int(ckRef)
        self.mutexCk.acquire()
        if (ckRef > self.ck):
            self.resp = ckRef + 1
        else:
            self.resp = self.ck + 1
        self.ck = self.resp
        self.mutexCk.release()
        return self.resp


